import os
import shutil

def move_files_with_prefix(source_folder, destination_folder, prefixes, file_extensions):
    """移动具有指定前缀的文件，并打印进度"""
    files_moved = 0
    total_files = sum(1 for prefix in prefixes for file in os.listdir(source_folder) if file.startswith(prefix) and file.endswith(tuple(file_extensions)))

    for prefix in prefixes:
        for file_name in os.listdir(source_folder):
            if file_name.startswith(prefix) and file_name.endswith(tuple(file_extensions)):
                shutil.move(os.path.join(source_folder, file_name),
                            os.path.join(destination_folder, file_name))
                files_moved += 1
                print(f"已移动 {files_moved}/{total_files} 个文件: {file_name}")

source_folder = 'F:\图像处理数据集\VOC2012\objdetect-pictures/trainval'    # 源图片文件夹
destination_folder = 'F:\图像处理数据集\VOC2012\objdetect-pictures/val'  # 目标图片文件夹
txt_file = 'F:\图像处理数据集\VOC2012\ImageSets\Main/val.txt'   # txt文件夹

# 设置支持的文件扩展名
file_extensions = ['.jpg', '.jpeg', '.png', '.gif']

# 读取TXT文件中的每一行（每个图片前缀）
with open(txt_file, 'r') as file:
    prefixes = [line.strip() for line in file]

# 调用函数移动文件
move_files_with_prefix(source_folder, destination_folder, prefixes, file_extensions)
